<template>
  <PageContainer>
    <Header title="领卡信息" />
    <view class="image-container">
      <image src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg01.png" mode="widthFix"
        class="full-width-image" />
      <image src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg02.png" mode="widthFix"
        class="full-width-image" />

      <view class="form-body">
        <view class="form-title-container">
          <view class="form-title-block">
            <text class="form-title">领卡信息</text>
          </view>
        </view>

        <view class="form-border">
          <view class="form-container">
            <view class="form-item">
              <view class="form-label">
                <text class="required">*</text>
                <text>选择套餐</text>
              </view>
              <view class="package-selector" @tap="openPackageModal">
                <text v-if="selectedPackageIndex !== undefined && packageList[selectedPackageIndex]?.name"
                  class="pl-10">{{ packageList[selectedPackageIndex].name }}</text>
                <text v-else>
                  <text class="pl-10 input-placeholder">请选择套餐</text>
                  <text class="arrow-icon">&#xe77e;</text>
                </text>
              </view>
            </view>
            <view class="form-item">
              <view class="form-label">
                <text class="required">*</text>
                <text>姓名</text>
              </view>
              <input type="text" v-model="formData.userName" placeholder="请输入姓名" class="pl-10" />
            </view>
            <view class="form-item">
              <view class="form-label">
                <text class="required">*</text>
                <text>身份证号</text>
              </view>
              <input type="idcard" v-model="formData.cerNo" placeholder="请输入身份证号" class="pl-10" />
            </view>
            <view class="form-item">
              <view class="form-label">
                <text class="required">*</text>
                <text>联系电话</text>
              </view>
              <input type="number" v-model="formData.telno" placeholder="请输入联系电话" class="pl-10" />
            </view>
            <!-- <view class="form-item">
              <view class="form-label">
                <text class="required">*</text>
                <text>选择号码</text>
              </view>
              <view class="package-selector" @tap="openNumberModal">
                <text v-if="formData.servnumber" class="pl-10">{{ formData.servnumber }}</text>
                <text v-else>
                  <text class="pl-10 input-placeholder">请选择号码</text>
                  <text class="arrow-icon">&#xe77e;</text>
                </text>
              </view>
            </view> -->
            <view class="form-item">
              <view class="form-label">
                <text class="required">*</text>
                <text>收货区域</text>
              </view>
              <view class="area-picker-wrapper">
                <AreaPicker v-model="areaPickerValue" placeholder="请选择收货区域" />
              </view>
            </view>
            <view class="form-item">
              <view class="form-label">
                <text class="required">*</text>
                <text>详细地址</text>
              </view>
              <input type="text" v-model="formData.address" placeholder="请输入详细地址" class="pl-10" />
            </view>
          </view>
        </view>

        <view class="submit-btn-wrapper">
          <image src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg10.png"
            mode="widthFix" class="submit-btn-bg natural-breathing" @tap="handleSubmit" />
        </view>

        <view class="checkbox-wrapper">
          <checkbox-group @change="toggleAgreement">
            <checkbox value="1" :checked="isAgreed" style="transform:scale(0.8);margin-right: 10rpx;" />
          </checkbox-group>
          <view>
            <text class="agreement-text" @click="toggleAgreement">我已阅读并同意</text>
            <template v-for="(item, index) in agreements" :key="index">
              <text class="agreement-link" @tap="toAgreement(item)">《{{ item.title }}》<template
                  v-if="index < (agreements?.length || 0) - 1">、</template></text>
            </template>
          </view>
        </view>
      </view>

      <image src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg04.png" mode="widthFix"
        class="full-width-image" />
      <image src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg05.png" mode="widthFix"
        class="full-width-image" />
      <image src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg06.png" mode="widthFix"
        class="full-width-image" />
      <image src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg07.png" mode="widthFix"
        class="full-width-image qrcode-image" show-menu-by-longpress
        @longpress="saveImage('https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg07.png')" />
      <image src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg08.png" mode="widthFix"
        class="full-width-image" />
      <image src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg09.jpg" mode="widthFix"
        class="full-width-image qrcode-image" show-menu-by-longpress
        @longpress="saveImage('https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg09.jpg')" />
    </view>

    <!-- 套餐选择弹窗 -->
    <ShowModal v-model="showPackageModal" title="请选择套餐" :showCancel="false" :isMaskClick="true" confirmColor="#FF6B35"
      cancelColor="#6B3A1D">
      <template #content>
        <view class="package-options">
          <view v-for="(item, index) in packageList" :key="index" class="package-option disFlxCC"
            :class="{ 'package-option-active': selectedPackageIndex === index }" @tap="selectPackage(index)">
            <view class="package-price">¥{{ item.price }}<text class="package-unit">/月</text></view>
            <view class="py-3">{{ item.desc }}</view>
            <view class="package-details">{{ item.name }}</view>
          </view>
        </view>
      </template>
    </ShowModal>

    <!-- 号码选择弹窗 -->
    <!-- <ShowModal v-model="showNumberModal" title="请选择号码" :showCancel="false" :isMaskClick="true" confirmColor="#FF6B35"
      cancelColor="#6B3A1D">
      <template #content>
        <view class="number-options">
          <view v-if="numberList && numberList.length === 0" class="empty-tip">
            <text>请先选择套餐后再选择号码</text>
          </view>
          <view v-else v-for="(item, index) in numberList" :key="index" class="number-option disFlxCC"
            :class="{ 'number-option-active': selectedNumberIndex === index }" @tap="selectNumber(index)">
            <view class="number-value">{{ item.number }}</view>
          </view>
        </view>
      </template>
    </ShowModal> -->

    <!-- 提交成功弹窗 -->
    <ShowModal v-model="countdownVisible" title="领取成功" :showCancel="false" :showConfirm="true" :isMaskClick="false"
      confirmText="返回首页" @confirm="goToHomePage">
      <template #content>
        <view class="countdown-success">
          <view class="py-20">
            <text class="ali-icon icon-chenggong1" style="font-size: 96rpx; color: #65b85d"></text>
          </view>
          <view class="fontTC mb-20">信息已成功提交，请耐心等待快递！</view>
        </view>
      </template>
    </ShowModal>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import PageContainer from '@/components/PageContainer/index.vue'
import Header from '@/components/Header/index.vue'
import ShowModal from '@/components/ShowModal/index.vue'
import { navigateTo, switchTab, onLoad } from '@/router'
import AreaPicker from './areaPicker.vue'
import { chooseNumberList, receiptYDCard } from '@/api/activity'
import { useUserStoreWithOut } from '@/store/modules/user'
import { onShareAppMessage } from '@dcloudio/uni-app'
import { useAppShare } from '@/hooks/core/useAppShare'
import { TabbarPageEnum } from '@/enums/pageEnum'

const { setWxSharePath } = useAppShare();
// 获取用户store
const userStore = useUserStoreWithOut()

// 表单数据
const formData = ref({
  areaCode: '755', // 号码归属地编码，默认深圳
  areaName: '深圳', // 号码归属地名称
  mainprodid: '', // 商品编码
  mainprodname: '', // 商品名称
  userName: '', // 姓名
  cerNo: '', // 身份证号
  telno: userStore.userInfo?.phonenumber || '', // 联系电话

  servnumber: '', // 选择的号码

  province: '', // 省份
  addressCity: '', // 城市
  addressArea: '', // 区域
  address: '', // 详细地址

  sysUserName: userStore.userInfo?.userName || '', // 会邦用户名
  isReadAgree: 0, // 是否阅读并同意(0没有 1有)
  referenceNumber: '', // 推荐人号码（非必填）
  inviterKey: '' // 邀请人Key
})

onLoad((op) => {
  if(op.shareKey){
    formData.value.inviterKey = op.shareKey
  }
})

// 收货区域选择器的值
const areaPickerValue = ref([{ name: '广东省', code: '200' }, { name: '深圳市', code: '755' }, { name: '罗湖区', code: '440303' }])

// 使用watch监听areaPickerValue变化
watch(
  areaPickerValue,
  (value) => {
    console.log('地区选择', value);

    // 确保value是一个数组且包含省市区信息
    if (Array.isArray(value) && value.length === 3) {
      const province = value[0] as { name: string; code: string };
      const city = value[1] as { name: string; code: string };
      const area = value[2] as { name: string; code: string };

      // 更新表单数据
      formData.value.province = province.name
      formData.value.addressCity = city.name
      formData.value.addressArea = area.name
    }
  },
  { deep: true, immediate: true } // 深度监听数组变化
)

// 套餐选择相关
const showPackageModal = ref(false)
const selectedPackageIndex = ref<number | undefined>(undefined)

// 打开套餐选择弹窗
const openPackageModal = () => {
  showPackageModal.value = true
}

// 套餐数据
const packageList = ref([
{
    name: '深圳39元行业卡-社工（39元折29元）',
    price: '29',
    desc: '通话600分钟，流量50G',
    code: '1343646459204800512',
  },
  {
    name: '深圳99元行业卡-社工（99元折49元）',
    price: '49',
    desc: '通话1200分钟，流量70G',
    code: '1343646675087208448',
  }
])

// 选择套餐
const selectPackage = (index: number) => {
  selectedPackageIndex.value = index
  const selectedPackage = packageList.value[index]

  formData.value.mainprodid = selectedPackage.code
  formData.value.mainprodname = selectedPackage.name

  showPackageModal.value = false

  getNumberList()
}

// 号码选择相关
const numberList = ref<{ mobileno: string }[]>([])
const getNumberList = async () => {
  if (!formData.value.mainprodid) return
  const response = await chooseNumberList(
    formData.value.areaCode,
    formData.value.mainprodid,
    15, // 获取10个号码供选择
    ''
  )
  console.log(response, '获取号码接口返回');
  
  const { data, code } = response
  if(code === 0){
    if (data && data.code === 0) {
      numberList.value = data.data?.infos ?? [];
        // 默认选择第一个号码
      if (numberList.value.length > 0) {
        const randomNumber = Math.floor(Math.random() * numberList.value.length);
        formData.value.servnumber = numberList.value[randomNumber].mobileno
      }
    }else{
      uni.showToast({
        title: data?.msg || '获取号码列表失败',
        icon: 'none'
      })
    }
  }
}

// const showNumberModal = ref(false)
// const selectedNumberIndex = ref<number | undefined>(undefined)

// // 打开号码选择弹窗
// const openNumberModal = async () => {
//   showNumberModal.value = true
// }
// // 确定选择号码
// const selectNumber = (index: number) => {
//   selectedNumberIndex.value = index
//   formData.value.servnumber = numberList.value[index].number
//   showNumberModal.value = false
// }

// 协议相关
const isAgreed = ref(false)
interface AgreementItem {
  title: string;
  type: string;  // 新增type字段
}

const agreements = ref<AgreementItem[]>([
  {
    title: '电子渠道开户服务协议',
    type: 'electronicAgreement',
  },
  {
    title: '个人单位在通信企业申请通讯工具渠道信息网络犯罪集团诈骗犯罪要任务预想示范知书',
    type: 'fraudPreventionNotice',
  },
  {
    title: '解约条款',
    type: 'terminationAgreement',
  },
  {
    title: '中国移动广东公司电子渠道商品销售服务协议',
    type: 'salesServiceAgreement',
  },
  {
    title: '中国移动广东公司客户入网协议',
    type: 'networkEntryAgreement',
  },
  {
    title: '中国移动广东公司隐私和个人信息保护政策',
    type: 'privacyPolicy',
  }
]);

const toggleAgreement = () => {
  isAgreed.value = !isAgreed.value
  formData.value.isReadAgree = isAgreed.value ? 1 : 0
}

const toAgreement = (item: AgreementItem) => {
  navigateTo({ name: 'cardActivityAgreement', options: { type: item.type } }); // 传递type参数
};

// 身份证号正则校验
const validateIdCard = (idCard: string) => {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  return reg.test(idCard)
}

// 手机号正则校验
const validatePhone = (phone: string) => {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(phone)
}

// 成功弹窗显示状态
const countdownVisible = ref(false)

// 返回首页
const goToHomePage = () => {
  switchTab(TabbarPageEnum.BASE_HOME)
}

// 表单提交逻辑
const handleSubmit = async () => {
  console.log(formData.value, '表单数据');

  // 校验套餐选择
  if (!formData.value.mainprodid) {
    uni.showToast({ title: '请选择套餐', icon: 'none' })
    return
  }
  // 校验姓名
  if (!formData.value.userName) {
    uni.showToast({ title: '请输入姓名', icon: 'none' })
    return
  }
  // 校验身份证号
  if (!validateIdCard(formData.value.cerNo)) {
    uni.showToast({ title: '身份证号码格式不正确', icon: 'none' })
    return
  }
  // 校验手机号
  if (!validatePhone(formData.value.telno)) {
    uni.showToast({ title: '请输入正确的联系电话', icon: 'none' })
    return
  }
  // 校验收货区域
  if (!formData.value.province || !formData.value.addressCity || !formData.value.addressArea || !formData.value.address) {
    uni.showToast({ title: '请选择完整的收货地址', icon: 'none' })
    return
  }
  if (!isAgreed.value) {
    uni.showToast({ title: '请先同意服务协议', icon: 'none' })
    return
  }

  try {
    uni.showLoading({
      title: '提交中...'
    })

    // 提交表单
    const response = await receiptYDCard(formData.value)
    const { data, code } = response
    if(code === 0){
      if (data && data.code === 0) {
        uni.hideLoading()
        // 显示成功弹窗
        countdownVisible.value = true
      }else{
        if(data?.msg.indexOf('号码已售出') !== -1){
          await getNumberList();
          handleSubmit();
        }else if(data?.msg.indexOf('订单处理中') !== -1){
          uni.hideLoading();

          getNumberList();
          uni.showToast({
            title: '请勿频繁提交，稍后再试',
            icon: 'none'
          })
        }else{
          uni.hideLoading();
          uni.showToast({
            title: data?.msg || '提交失败，请重试',
            icon: 'none'
          })
        }
      }
    }else{uni.hideLoading()}
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '提交失败，请稍后重试',
      icon: 'none'
    })
    console.error('提交表单失败', error)
  }
}

// 保存图片
const saveImage = (url: string) => {
  uni.showActionSheet({
    itemList: ['保存图片'],
    success: () => {
      uni.downloadFile({
        url: url,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.showToast({
                  title: '保存成功',
                  icon: 'success'
                })
              },
              fail: (err) => {
                if (err.errMsg.includes('auth deny')) {
                  uni.showModal({
                    title: '提示',
                    content: '请授权保存图片到相册',
                    success: (res) => {
                      if (res.confirm) {
                        uni.openSetting()
                      }
                    }
                  })
                } else {
                  uni.showToast({
                    title: '保存失败',
                    icon: 'none'
                  })
                }
              }
            })
          }
        },
        fail: () => {
          uni.showToast({
            title: '图片下载失败',
            icon: 'none'
          })
        }
      })
    }
  })
}


/** 分享 */
onShareAppMessage((e) => {
  return {
    title: '深圳社工专属福利',
    path: setWxSharePath({ name: 'cardActivity' }),
    imageUrl: 'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg01.png',
  };
});
</script>

<style lang="scss" scoped>
.image-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.full-width-image {
  width: 100%;
  display: block;
  margin: 0;
  padding: 0;
}

.form-body {
  width: 100%;
  background-image: url('https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/mobile/cardActivityImg11.png');
  background-size: 100% auto;
  background-repeat: repeat;
  padding: 20rpx 0;
}

.form-title-container {
  display: flex;
  justify-content: center;
  margin: 30rpx 0 40rpx;
}

.form-title-block {
  background: #6B3A1D;
  padding: 16rpx 50rpx;
  border-radius: 10rpx;
  box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.2);
  position: relative;

  &::after {
    content: '';
    position: absolute;
    bottom: -14rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 0;
    height: 0;
    border-left: 14rpx solid transparent;
    border-right: 14rpx solid transparent;
    border-top: 14rpx solid #6B3A1D;
  }
}

.form-title {
  font-size: 42rpx;
  font-weight: bold;
  color: #FFF3D0;
  letter-spacing: 3rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

.form-border {
  position: relative;
  margin: 0 30rpx;
  padding: 3rpx;
  border-radius: 20rpx;
  background: #6B3A1D;
  box-shadow: 0 6rpx 16rpx rgba(107, 58, 29, 0.3);
}

.form-container {
  background-color: #FFF9E6;
  border-radius: 18rpx;
  padding: 30rpx 20rpx;
}

.form-item {
  margin-bottom: 24rpx;
  position: relative;
  display: flex;
  align-items: center;
  border-bottom: 2rpx solid rgba(107, 58, 29, 0.2);
  padding-bottom: 8rpx;
}

.form-label {
  min-width: 140rpx;
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #6B3A1D;
  font-weight: 500;
}

.required {
  color: #FF6B35;
  margin-right: 4rpx;
  font-size: 28rpx;
}

input {
  flex: 1;
  height: 70rpx;
  border: none;
  font-size: 28rpx;
  background-color: transparent;
  color: #333;
  font-weight: 400;
}

.package-selector {
  flex: 1;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 28rpx;
  color: #333;
}

.area-picker-wrapper {
  flex: 1;
}

.arrow-icon {
  font-family: "ali-icon";
  color: #999996;
  font-size: 28rpx;
  margin-left: 10rpx;
}

.agreement {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20rpx 0;
}

.checkbox-wrapper {
  display: flex;
  align-items: start;
  padding: 20rpx;
}

.agreement-text {
  font-size: 26rpx;
  color: #6B3A1D;
  margin-right: 4rpx;
  user-select: none;
  flex-shrink: 0;
  /* 防止文字被选中 */
}

.agreement-link {
  font-size: 26rpx;
  color: #FF6B35;
  text-decoration: none;
  user-select: none;
  flex-shrink: 0;

  &:active {
    opacity: 0.8;
  }
}

.submit-btn-wrapper {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 30rpx;
}

.submit-btn-bg {
  width: 70%;
  height: auto;
  filter: drop-shadow(0 4rpx 8rpx rgba(255, 107, 53, 0.4));
  transition: all 0.3s;
}

.submit-btn-bg:active {
  opacity: 0.9;
  transform: translateY(2rpx);
}

.natural-breathing {
  animation: natural-breathing 1.5s ease-in-out infinite;
}

@keyframes natural-breathing {
  0% {
    transform: scale(0.95);
    filter: drop-shadow(0 4rpx 8rpx rgba(255, 107, 53, 0.3));
  }

  50% {
    transform: scale(1.05);
    filter: drop-shadow(0 12rpx 20rpx rgba(255, 107, 53, 0.6));
  }

  100% {
    transform: scale(0.95);
    filter: drop-shadow(0 4rpx 8rpx rgba(255, 107, 53, 0.3));
  }
}

/* 套餐选择弹窗样式 */
.package-options {
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 20rpx;
}

.package-option {
  width: 100%;
  min-height: 120rpx;
  padding: 20rpx;
  border-radius: 12rpx;
  background-color: #FFF9E6;
  font-size: 28rpx;
  color: #6B3A1D;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  border: 2rpx solid rgba(107, 58, 29, 0.2);
  box-shadow: 0 2rpx 4rpx rgba(107, 58, 29, 0.1);
  box-sizing: border-box;
  transition: all 0.2s ease;
  margin: 20rpx 0 10rpx 0;
}

.package-option-active {
  background-color: #FF6B35;
  color: #fff;
  border: 2rpx solid #FF6B35;
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 8rpx rgba(255, 107, 53, 0.2);
}

.package-left {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.package-price {
  font-size: 40rpx;
  font-weight: bold;
  line-height: 1;
}

.package-unit {
  font-size: 24rpx;
  font-weight: normal;
  margin-left: 4rpx;
}

.package-details {
  font-size: 26rpx;
  opacity: 0.9;
  line-height: 1.4;
}

.form-item {
  ::v-deep .input-placeholder {
    color: #999996 !important;
    font-size: 27rpx;
    font-weight: 400;
  }
}

.qrcode-image {
  position: relative;

  &::after {
    content: '长按识别或保存';
    position: absolute;
    bottom: 20rpx;
    left: 50%;
    transform: translateX(-50%);
    background-color: rgba(0, 0, 0, 0.6);
    color: #fff;
    font-size: 24rpx;
    padding: 8rpx 20rpx;
    border-radius: 20rpx;
    white-space: nowrap;
  }
}

/* 成功弹窗样式 */
.countdown-success {
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 号码选择弹窗样式 */
.number-options {
  width: 100%;
  padding: 20rpx;
  box-sizing: border-box;
  max-height: 500rpx;
  overflow-y: auto;
}

.number-option {
  width: 100%;
  height: 100rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
  border-radius: 12rpx;
  background-color: #FFF9E6;
  color: #6B3A1D;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  border: 2rpx solid rgba(107, 58, 29, 0.2);
  box-shadow: 0 2rpx 4rpx rgba(107, 58, 29, 0.1);
  box-sizing: border-box;
  transition: all 0.2s ease;
}

.number-option:last-child {
  margin-bottom: 0;
}

.number-option-active {
  background-color: #FF6B35;
  color: #fff;
  border: 2rpx solid #FF6B35;
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 8rpx rgba(255, 107, 53, 0.2);
}

.number-value {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
}

.empty-tip,
.loading-tip {
  width: 100%;
  text-align: center;
  padding: 40rpx 20rpx;
  color: #999;
  font-size: 28rpx;
}

.form-item {
  ::v-deep .input-placeholder {
    color: #999996 !important;
    font-size: 27rpx;
    font-weight: 400;
  }
}
</style>